//
//  OANameListController.m
//  OASystem
//
//  Created by zhoupengfei on 15/4/21.
//  Copyright (c) 2015年 zpf. All rights reserved.
//

#import "FSwaitdetailViewController.h"
#import "daibanViewController.h"
#import "OANameListController.h"
#import "HttpTools.h"
#import "daiyueViewController.h"
#import "GDataDefines.h"
#import "MBProgressHUD.h"
#import "OANameListModel.h"
#import "OASubNameListModel.h"
#import "HeaderView.h"
#import "OANewEmailController.h"
#import "OANewSMSViewController.h"
#import "MKTreeView.h"
#import "zfyjViewController.h"
#import "kszfViewController.h"
@interface OANameListController ()<HeaderViewDelegate,HeaderViewDelegate2>


@property (nonatomic,strong)MKTreeView *mkView;


@end

@implementation OANameListController

-(NSMutableArray*)groupArray{

    if (_groupArray == nil) {
        _groupArray = [NSMutableArray array];
    }
    return _groupArray;
}

-(NSMutableArray*)rowArray{
    
    if (_rowArray == nil) {
        _rowArray = [NSMutableArray array];
    }
    return _rowArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
         [self loadData];

         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(xxx:) name:@"11111" object:nil];

}
#pragma mark 加载网络数据
-(void)loadData{


//NSString *filePath = [[NSBundle mainBundle] pathForResource:@"json" ofType:nil];
//    NSString *jsonString = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
//self.dataSource = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
   NSString * url = nil;

    NSString * method = nil;
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
//    NSArray *  array = @[@{@"userId":userId}];;
    url =KExchTree;
    NSArray * array = nil;
    if ([self.type isEqualToString:@"CountyDataType" ]) {
        method = KDepTree;
        if (self.identifierString) {
               array = @[@{@"path":self.identifierString},@{@"userId":userId}];
        }else{
               array = @[@{@"userId":userId}];
        }
     
    }else if ([self.type isEqualToString:@"UnitDataType" ]){
        method = KLocalTree;
        array = @[@{@"userId":userId}];
    }else if([self.type isEqualToString:@"DepartmentDataType" ]){
        method = KsTree;
        url = KExchTree;
        array = @[@{@"userId":userId}];
    }else{
            url = KExchTree;

            method = KLocalTree;
        array = @[@{@"userId":userId}];

    }
[HttpTools requestWithURL:url arrays:array method:method success:^(id JSON) {
NSLog(@"%@",JSON);
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        NSArray * tempArray = JSON[@"data"];
        NSDictionary *dict = [tempArray firstObject];
NSArray *dataArray = dict[@"Parent"];
MKTreeView *view = [[MKTreeView instanceView] initTreeWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) dataArray:dataArray haveHiddenSelectBtn:NO haveHeadView:NO isEqualX:NO];
//    view.delegate = self;
    self.mkView = view;
    [self.view addSubview:view];

    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
    }];



// MKTreeView *view = [[MKTreeView instanceView] initTreeWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) dataArray:dataArray haveHiddenSelectBtn:NO haveHeadView:NO isEqualX:NO];
////    view.delegate = self;
//    self.mkView = view;

//    [self.view addSubview:view];

}

- (void)xxx:(NSNotification *)noti{
 NSMutableArray *array = noti.userInfo[@"text"];
    
     NSString *str = nil;
     NSString *str2 = nil;

  for (NSString *str1 in array) {
    if (str.length == 0) {
   str  = [NSString stringWithFormat:@"%@",str1];
   str2 = [NSString stringWithFormat:@"%@",str1];

}else {
   str = [NSString stringWithFormat:@"%@,%@",str1,str];
   str2 = [NSString stringWithFormat:@"%@;%@",str1,str];

}
    
    
    
  }
    _selectPersons2 = str2;

  _selectPersons = str;




}
#pragma mark 取消
-(IBAction)cancle:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark 确定
-(IBAction)confir:(id)sender{
//    NSMutableArray * tempArray = [NSMutableArray array];
//    for (OANameListModel * nameLisModel in self.groupArray) {
//        for (OASubNameListModel * subModel in nameLisModel.subArray) {
//            if (subModel.isSelected) {
//                [tempArray addObject:subModel];
//                if ([self.delegate respondsToSelector:@selector(didSelecteName:)]) {
//                    [self.delegate didSelecteName:tempArray];
//                }
//            }
//        }
//    }
//    for (UIViewController * VC in self.navigationController.viewControllers) {
//        if ([VC isKindOfClass:[OANewEmailController class]]||[VC isKindOfClass:[OANewSMSViewController class]]) {
////            [self.navigationController popToViewController:VC animated:YES];
//  [self.navigationController popToViewController:self.navigationController.viewControllers[2] animated:YES];
//        }
//    }
 if (_selectPersons) {
    

    
if ([_string isEqualToString:@"fasong"]){
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"unid":self.fileId},@{@"userId":userId},@{@"segment":self.setpString},@{@"staff":_selectPersons},@{@"ryorder":@"1"},@{@"famxml":self.body}];
    
    NSLog(@"%@",array);

    [HttpTools postWithURL:KexchdataURL arrays:array method:KSetStaffListDeliVerMethod success:^(id JSON) {
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
        GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: [JSON dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        GDataXMLElement *rootElement = [doc rootElement];
        NSArray *arrData= [rootElement elementsForName:@"info"];
        NSString * message= nil;
        for (GDataXMLElement * subXMLElement in arrData) {
            GDataXMLElement * element = [[subXMLElement elementsForName:@"msg"] objectAtIndex:0];
            message  = [element stringValue];
        }
    
            [self.view makeToast:@"发送成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOADetailData" object:nil];
 [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];

        
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
        [self.view makeToast:@"发送失败"];
    }];
} else if ([_seltype isEqualToString:@"daiban"]) {
        [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

//        NSString * selectPersons = [tempArray componentsJoinedByString:@","];
  NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"unid":self.fileId},@{@"userId":userId},@{@"segment":self.setpString},@{@"staff":_selectPersons},@{@"ryorder":@"0"},@{@"famxml":self.body}];
     [HttpTools postWithURL:KexchdataURL arrays:array method:KSetStaffListDeliVerMethod success:^(id JSON) {
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
//        self.rightItem.enabled = YES;
        GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: [JSON dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        GDataXMLElement *rootElement = [doc rootElement];
        NSArray *arrData= [rootElement elementsForName:@"info"];
        NSString * message= nil;
        for (GDataXMLElement * subXMLElement in arrData) {
            GDataXMLElement * element = [[subXMLElement elementsForName:@"msg"] objectAtIndex:0];
            message  = [element stringValue];
        }
    if ([message isEqualToString:@"11"]) {
       [self.view makeToast:@"发送成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOADetailData" object:nil];
//            [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
  for (UIViewController * VC in self.navigationController.viewControllers) {
        if ([VC isKindOfClass:[daibanViewController class]]) {
            [self.navigationController popToViewController:VC animated:YES];
            break;
        }
    }
}else{
        [self.view makeToast:@"发送失败"];

}
        
    
        
    } failure:^(NSError *error) {
//        self.rightItem.enabled = YES;
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
        [self.view makeToast:@"发送失败"];
    }];
    
}else if ([_seltype isEqualToString:@"chuanyue"]){

   NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSString * password = [[NSUserDefaults standardUserDefaults]objectForKey:@"pwdId"];
//    NSString *string = [tempArray componentsJoinedByString:@";"];
//,@{@"yj":_textString}
        NSArray * array = @[@{@"unid":_fileId},@{@"sName":userId},@{@"ryxx":_selectPersons}];

    [HttpTools requestWithURL:KexchgeneralURL arrays:array method:@"ReadFileDistribute" success:^(id JSON) {
    
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
           if ([[NSString stringWithFormat:@"%@",JSON] isEqualToString:@"20"]) {
             [self.view makeToast:@"发送成功"];
                             [NSThread sleepForTimeInterval:1.0];

  for (UIViewController * VC in self.navigationController.viewControllers) {
        if ([VC isKindOfClass:[daiyueViewController class]]) {
            [self.navigationController popToViewController:VC animated:YES];
            break;
        }
//         if ([VC isKindOfClass:[daibanViewController class]]) {
//            [self.navigationController popToViewController:VC animated:YES];
//            break;
//        }
    }
        }else{             [self.view makeToast:@"发送失败"];

     
        }
     
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [self.view makeToast:@"发送失败"];
    }];






}else if ([_seltype isEqualToString:@"daibanchuanyue"]){

   NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSString * password = [[NSUserDefaults standardUserDefaults]objectForKey:@"pwdId"];
//    NSString *string = [tempArray componentsJoinedByString:@";"];
        NSArray * array = @[@{@"unid":_fileId},@{@"sName":userId},@{@"ryxx":_selectPersons2}];

    [HttpTools requestWithURL:KexchdataURL arrays:array method:@"ReadFileDistribute" success:^(id JSON) {
    
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
           if ([[NSString stringWithFormat:@"%@",JSON] isEqualToString:@"20"]) {
             [self.view makeToast:@"发送成功"];
                             [NSThread sleepForTimeInterval:1.0];

  for (UIViewController * VC in self.navigationController.viewControllers) {
//        if ([VC isKindOfClass:[daiyueViewController class]]) {
//            [self.navigationController popToViewController:VC animated:YES];
//            break;
//        }
         if ([VC isKindOfClass:[daibanViewController class]]) {
            [self.navigationController popToViewController:VC animated:YES];
            break;
        }
    }
        }else{             [self.view makeToast:@"发送失败"];

     
        }
     
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [self.view makeToast:@"发送失败"];
    }];






}else if ([_seltype isEqualToString:@"zhuanfaxx"]){

   NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSString * password = [[NSUserDefaults standardUserDefaults]objectForKey:@"pwdId"];
//    NSString *string = [tempArray componentsJoinedByString:@";"];
        NSArray * array = @[@{@"unid":_fileId},@{@"sName":userId},@{@"ryxx":_selectPersons2}];

    [HttpTools requestWithURL:KexchangeSubstanceURL arrays:array method:@"exchangeFileDistribute" success:^(id JSON) {
    
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
           if ([[NSString stringWithFormat:@"%@",JSON] isEqualToString:@"20"]) {
             [self.view makeToast:@"发送成功"];
                             [NSThread sleepForTimeInterval:1.0];

  for (UIViewController * VC in self.navigationController.viewControllers) {
        if ([VC isKindOfClass:[FSwaitdetailViewController class]]) {
            [self.navigationController popToViewController:VC animated:YES];
            break;
        }
    }

        }else{             [self.view makeToast:@"发送失败"];

     
        }
     
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [self.view makeToast:@"发送失败"];
    }];






}


else if ([_seltype isEqualToString:@"zhuanfa"]){

   NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSString * password = [[NSUserDefaults standardUserDefaults]objectForKey:@"pwdId"];
//    NSString *string = [tempArray componentsJoinedByString:@","];
  NSString *   body =  [NSString stringWithFormat:@"&lt;?xml version=\'1.0\' encoding=\'utf-8\'?&gt;\n"
         "&lt;交换 xmlns=\'exch.jhsx.gov.cn/data\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\'&gt;\n"
         "&lt;数据&gt;\n"
         "&lt;数据要素&gt;\n"
         "&lt;unid&gt; %@ &lt;/unid&gt;\n"
         "&lt;SendTo&gt; %@ &lt;/SendTo&gt;\n"
         "&lt;/数据要素&gt;\n"
         "&lt;附件&gt;\n"
         "&lt;/附件&gt;\n"
         "&lt;/数据&gt;\n"
         "&lt;/交换&gt;"
              ,self.fileId,_selectPersons];
        NSArray * array = @[@{@"sName":userId},@{@"sPass":password},@{@"formxml":body}];

    [HttpTools postWithURL:KexchmailURL arrays:array method:@"trunsendMail" success:^(id JSON) {
      GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: [JSON dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        GDataXMLElement *rootElement = [doc rootElement];
        NSArray *arrData= [rootElement elementsForName:@"info"];
        NSString * message= nil;
        for (GDataXMLElement * subXMLElement in arrData) {
            GDataXMLElement * element = [[subXMLElement elementsForName:@"msg"] objectAtIndex:0];
            message  = [element stringValue];
        }
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
           if ([message isEqualToString:@"20"]) {
             [self.view makeToast:@"发送成功"];
                             [NSThread sleepForTimeInterval:1.0];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshData" object:nil]; //刷新发件箱，收件箱 数据

  for (UIViewController * VC in self.navigationController.viewControllers) {
        if ([VC isKindOfClass:[ zfyjViewController class]]) {
            [self.navigationController popToViewController:VC animated:YES];
            break;
        }
    }
    
        }else{             [self.view makeToast:@"发送失败"];

     
        }
     
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [self.view makeToast:@"发送失败"];
    }];






}else if ([_seltype isEqualToString:@"kszhuanfa"]){

   NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSString * password = [[NSUserDefaults standardUserDefaults]objectForKey:@"pwdId"];
//    NSString *string = [tempArray componentsJoinedByString:@","];
  NSString *   body =  [NSString stringWithFormat:@"&lt;?xml version=\'1.0\' encoding=\'utf-8\'?&gt;\n"
         "&lt;交换 xmlns=\'exch.jhsx.gov.cn/data\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\'&gt;\n"
         "&lt;数据&gt;\n"
         "&lt;数据要素&gt;\n"
         "&lt;unid&gt; %@ &lt;/unid&gt;\n"
         "&lt;SendTo&gt; %@ &lt;/SendTo&gt;\n"
         "&lt;/数据要素&gt;\n"
         "&lt;附件&gt;\n"
         "&lt;/附件&gt;\n"
         "&lt;/数据&gt;\n"
         "&lt;/交换&gt;"
              ,self.fileId,_selectPersons];
        NSArray * array = @[@{@"sName":userId},@{@"sPass":password},@{@"formxml":body}];

    [HttpTools postWithURL:KexchksmailURL arrays:array method:@"trunsendMail" success:^(id JSON) {
      GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: [JSON dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        GDataXMLElement *rootElement = [doc rootElement];
        NSArray *arrData= [rootElement elementsForName:@"info"];
        NSString * message= nil;
        for (GDataXMLElement * subXMLElement in arrData) {
            GDataXMLElement * element = [[subXMLElement elementsForName:@"msg"] objectAtIndex:0];
            message  = [element stringValue];
        }
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
           if ([message isEqualToString:@"20"]) {
             [self.view makeToast:@"发送成功"];
                             [NSThread sleepForTimeInterval:1.0];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshData" object:nil]; //刷新发件箱，收件箱 数据

    for (UIViewController * VC in self.navigationController.viewControllers) {
        if ([VC isKindOfClass:[ kszfViewController class]]) {
            [self.navigationController popToViewController:VC animated:YES];
            break;
        }
    }

 
        }else{             [self.view makeToast:@"发送失败"];

     
        }
     
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [self.view makeToast:@"发送失败"];
    }];






}




else{
NSMutableArray * tempArray = [NSMutableArray array];
    for (OANameListModel * nameLisModel in self.groupArray) {
        for (OASubNameListModel * subModel in nameLisModel.subArray) {
            if (subModel.isSelected) {
                [tempArray addObject:subModel];
                if ([self.delegate respondsToSelector:@selector(didSelecteName:)]) {
                    [self.delegate didSelecteName:tempArray];
                }
            }
        }
            }
    for (UIViewController * VC in self.navigationController.viewControllers) {
        if ([VC isKindOfClass:[ OANewEmailController class]]) {
            [self.navigationController popToViewController:VC animated:YES];
            break;
        }
    }
}
}
else{

[self.view makeToast:@"对不起，请选择人员"];
}
}



-(void)clickHeaderView{
    [self.tableView reloadData];
}-(void)clickHeaderView2{
    [self.tableView reloadData];
}


#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
   return self.groupArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    OANameListModel * nameListModel = self.groupArray[section];
    NSArray * tempArray = nameListModel.subArray;
    return  nameListModel.isOpen ? tempArray.count : 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID" forIndexPath:indexPath];
    OANameListModel * nameListModel = self.groupArray[indexPath.section];
    OASubNameListModel * subModel = nameListModel.subArray[indexPath.row];
    cell.textLabel.text = subModel.value;
    cell.textLabel.font = [UIFont systemFontOfSize:13];
    if (subModel.isSelected) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    HeaderView * headView = [HeaderView headerViewWithTableView:tableView];
    headView.delegate = self;
    headView.groupModel= self.groupArray[section];
    return headView;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    OANameListModel * nameListModel = self.groupArray[indexPath.section];
    OASubNameListModel * subModel = nameListModel.subArray[indexPath.row];
    subModel.isSelected = !subModel.isSelected;
    [self.tableView reloadData];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}

@end
